from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
import time
from app.models import User


class MD1(MiddlewareMixin):
    def process_request(self, req):
        if req.path != "/api/login":
            try:
                token = req.META.get("HTTP_AUTHORIZATION").split(" ")[1]
                data = list(User.objects.filter(token=token).values())
                if data is None:
                    return JsonResponse({"code": 413, "message": "token无效"})
                elif float(data[0]["token_end"]) < time.time():
                    return JsonResponse({"code": 414, "message": "token过期"})
            except AttributeError:
                return JsonResponse({"code": 413, "message": "token无效"})
            except IndexError:
                return JsonResponse({"code": 413, "message": "token无效"})

